package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增地址
     * @param addressDto
     */
    @Override
    public void saveAddress(AddressBookUpsertReqDTO addressDto) {
        Long userId = UserContext.currentUserId();
        AddressBook addressBook = BeanUtils.copyBean(addressDto, AddressBook.class);
        // 设置用户id
        addressBook.setUserId(userId);
        String[] location = addressDto.getLocation().split(",");
        // 分别设置经度和纬度
        addressBook.setLon(Double.parseDouble(location[0]));
        addressBook.setLat(Double.parseDouble(location[1]));
        // 用户的默认地址只能有1个，如果要设置当前地址为默认地址，则将原来的默认地址设置为0
        Boolean isDefault = addressDto.getIsDefault() == 1 ? true : false;
        boolean success = lambdaUpdate()
                .eq(AddressBook::getUserId, userId)
                .eq(isDefault, AddressBook::getIsDefault, 1)
                .set(AddressBook::getIsDefault, 0)
                .update();
        if (!success) {
            throw new DBException("数据库操作失败");
        }
        save(addressBook);
    }

    /**
     * 分页查询地址簿
     * @param query
     * @return
     */
    @Override
    public PageResult<AddressBook> pageQuery(AddressBookPageQueryReqDTO query) {
        Long userId = UserContext.currentUserId();
        // Page<AddressBook> page = lambdaQuery()
        //         .eq(AddressBook::getUserId, userId)
        //         .page(query.toMpPage("create_time", false));
        // List<AddressBook> addressList = page.getRecords();
        PageResult<AddressBook> result = PageHelperUtils.selectPage(query, () -> baseMapper.queryAddrList(userId));
        if (CollUtils.isEmpty(result.getList())) {
            return PageResult.empty(0L, 0L);
        }
        return result;
    }

    /**
     * 获取地址详情
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressDetail(Long id) {
        Long userId = UserContext.currentUserId();
        AddressBook addr = lambdaQuery()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted, 0)
                .one();
        return addr;
    }

    /**
     * 修改地址
     * @param id
     * @param addressDto
     */
    @Override
    public void updateAddress(Long id, AddressBookUpsertReqDTO addressDto) {
        Long userId = UserContext.currentUserId();
        AddressBook old = getById(id);
        if (ObjectUtil.isEmpty(old)) {
            throw new DBException("地址不存在");
        }
        String name = addressDto.getName();
        String phone = addressDto.getPhone();
        Integer isDefault = addressDto.getIsDefault();
        String address = addressDto.getAddress();
        String city = addressDto.getCity();
        String province = addressDto.getProvince();
        String county = addressDto.getCounty();
        String location = addressDto.getLocation();
        Double lon = old.getLon();
        Double lat = old.getLat();
        if (StringUtils.isNotBlank(location)) {
            lon = Double.parseDouble(location.split(",")[0]);
            lat = Double.parseDouble(location.split(",")[1]);
        }
        if (isDefault == 1) {
            // 将其他地址设置为非默认地址
            boolean success = lambdaUpdate()
                    .eq(AddressBook::getUserId, userId)
                    .eq(AddressBook::getIsDefault, 1)
                    .set(AddressBook::getIsDefault, 0)
                    .update();
            if (!success) {
                throw new DBException("数据库操作失败");
            }
        }
        boolean success = lambdaUpdate()
                .eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDeleted, 0)
                .set(name != null, AddressBook::getName, name)
                .set(phone != null, AddressBook::getPhone, phone)
                .set(isDefault != null, AddressBook::getIsDefault, isDefault)
                .set(lon != null, AddressBook::getLon, lon)
                .set(lat != null, AddressBook::getLat, lat)
                .set(address != null, AddressBook::getAddress, address)
                .set(city != null, AddressBook::getCity, city)
                .set(province != null, AddressBook::getProvince, province)
                .set(county != null, AddressBook::getCounty, county)
                .update();
        if (!success) {
            throw new DBException("修改地址失败");
        }
    }

    /**
     * 批量删除地址
     * @param ids
     */
    @Override
    public void deleteAddressBatch(List<Long> ids) {
        Long userId = UserContext.currentUserId();
        boolean success = lambdaUpdate()
                .eq(AddressBook::getUserId, userId)
                .in(AddressBook::getId, ids)
                .remove();
        if (!success) {
            throw new DBException("删除地址失败");
        }
    }

    /**
     * 设置默认地址
     * @param id
     * @param isDefault
     */
    @Override
    public void setDefaultAddress(Long id, Integer isDefault) {
        Long userId = UserContext.currentUserId();
        AddressBook addr = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
        if (isDefault == 1 && ObjectUtils.isNotEmpty(addr)) {
            addr.setIsDefault(0);
            updateById(addr);
        }
        boolean success = lambdaUpdate()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getId, id)
                .set(AddressBook::getIsDefault, isDefault)
                .update();
        if (!success) {
            throw new DBException("设置默认地址失败");
        }
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public AddressBook getDefaultAddress() {
        Long userId = UserContext.currentUserId();
        AddressBook addr = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1)
                .one();
        return addr;
    }
}
